#ifndef _FUNCTIONJSONENCODE_HPP
#define _FUNCTIONJSONENCODE_HPP

#include "CJsonObject.hpp"

namespace builtin {
	class FunctionJsonEncode {
	public:
		Object* operator()(std::vector<Object*> argLists) {
			if (argLists.size() != 1) {
				return new Error("json_encode function must have 1 parameter");
			}
			if (argLists[0]->Type() != ARRAY_OBJECT) {
				return new Error("json_encode function first parameter must be array");
			}
			neb::CJsonObject json;
			ArrayObject* arr = dynamic_cast<ArrayObject*>(argLists[0]);
			toJson(arr, json);
			return new StringObject(json.ToString());
		}
	private:
		void toJson(ArrayObject* arr, neb::CJsonObject& json) {
			bool str_flag = false;
			for (auto& itr : arr->_elements) {
				if (itr.second->_val->Type() == ARRAY_OBJECT) {
					neb::CJsonObject arr_json;
					ArrayObject* arr_obj = dynamic_cast<ArrayObject*>(itr.second->_val);
					toJson(arr_obj, arr_json);
					if (!arr->str_flag) {
						json.Add(arr_json);
					}
					else {
						json.Add(itr.second->_key->examine(), arr_json);
					}
					
				}
				else {
					if (!arr->str_flag) {
						json.Add(itr.second->_val->examine());
					}
					else {
						json.Add(itr.second->_key->examine(), itr.second->_val->examine());
					}
				}
			}
		}
	};
}

#endif // !_FUNCTIONJSONENCODE_HPP
